using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Claims;
using UniversalAdminSystem.Application.PermissionManagement.Interfaces;

namespace UniversalAdminSystem.Api.Attributes;

/// <summary>
/// 权限验证特性
/// 用于标记需要特定权限的API接口
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] //指定该特性可用于 类（Controller） 或 方法（Action） 级别。
public class RequirePermissionAttribute : Attribute, IAsyncAuthorizationFilter
{
    private readonly string _permissionCode;

    public RequirePermissionAttribute(string permissionCode)
    {
        _permissionCode = permissionCode;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        try
        {
            
            // 获取用户ID
            var userId = context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            System.Console.WriteLine($"userId: {userId}" ?? "null");
            if (string.IsNullOrEmpty(userId))
            {   
                Console.WriteLine($"userId: {context.HttpContext.User.Identity?.Name}");
                context.Result = new UnauthorizedResult();
                return;
            }

            // 获取权限检查服务
            var service = context.HttpContext.RequestServices.GetService<IPermissionCheckService>();
            if (service == null)
            {
                context.Result = new StatusCodeResult(500);
                return;
            }

            // 检查用户是否有指定权限
            var hasPermission = await service.CheckUserPermissionAsync(Guid.Parse(userId), _permissionCode);
            System.Console.WriteLine($"hasPermission: {hasPermission}");
            if (!hasPermission)
            {
                context.Result = new StatusCodeResult(401);
                return;
            }
        }
        catch (Exception ex)
        {
            // 记录错误并返回500
            Console.WriteLine($"权限验证错误: {ex.Message}");
            context.Result = new StatusCodeResult(500);
        }
    }
} 